#
#-*- coding: utf-8 -*-
#

from google.appengine.api import xmpp
from google.appengine.ext import db
from datetime import datetime

class Rec(db.Model):
	user = db.StringProperty(required=True)
	dtadd = db.DateTimeProperty(required=True)
	desc = db.TextProperty(required=True)

def recProc(sender,cmd):
	pcmd = cmd.strip()
	pos = pcmd.find(' ')
	
	verb = pcmd
	ar = ''
	if pos != -1 :
		verb = pcmd[:pos]
		ar = pcmd[pos+1:]

	if(verb=='-del'):
		recDel(sender,ar)
	elif(verb=='-add'):
		recAdd(sender,ar)
	elif(verb=='-list'):
		recList(sender,ar)
	elif(verb=='-clear'):
		recClear(sender)
	else:
		recHelp(sender)

def recList(sender, ar):
	try:
		num = int(ar)
	except:
		num = 100000
	
	query = db.GqlQuery("select * from Rec where user = :1 order by dtadd DESC",sender)
	result = query.fetch(num)
	ret = 'get %d rec items for you: ' % len(result)
	for item in result :
		ret += '\n ' + "["+str(item.key().id())+"] " + item.desc + '(' + item.dtadd.ctime()+')'
	xmpp.send_message(sender,ret)

def recAdd(sender,item):
	dnow = datetime.utcnow()
	td = Rec(user=sender,desc=item,dtadd=dnow)
	td.put()
	xmpp.send_message(sender,'rec item added :)')

def recDel(sender,id):
	query = db.GqlQuery("select * from Rec where user = :1",sender)
	for item in query :
		if str(item.key().id()) == id :
			item.delete()
			xmpp.send_message(sender,'rec item deleted :)')
			return
	
	xmpp.send_message(sender,'rec item not found :(')

def recClear(sender):
	query = db.GqlQuery("select * from Rec where user = :1",sender)
	db.delete(query)
	xmpp.send_message(sender,'you have no items now')

def recHelp(sender):
	ret ='''rec has some subcmd :
			\\rec -add newitem
			\\rec -del itemid
			\\rec [-list [n]] 
			\\rec -clear 
			\\rec -help 
			'''
	xmpp.send_message(sender,ret)
